#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "gui/newfiledialog.h"
#include "config/applicationconfiguration.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(ui->actionNewFile, SIGNAL(triggered()), this, SLOT(newFileCliked()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setServerStatus(QString status){

    ui->serverStatus->setText(status);
}

void MainWindow::addClient(QString client){

    int rc = ui->connectedClients->rowCount();
    ui->connectedClients->insertRow(rc);

    QTableWidgetItem* newItem = new QTableWidgetItem(client);
    ui->connectedClients->setItem(rc, 0, newItem);
    ui->connectedClients->item(rc, 0)->setTextAlignment(Qt::AlignCenter);

    ui->logField->setPlainText(ui->logField->toPlainText() + "Accepted connection from " + client + ".\n");
}

void MainWindow::removeClient(QString client){

    QList<QTableWidgetItem*> list = ui->connectedClients->findItems(client, Qt::MatchContains);

    ui->connectedClients->removeRow(ui->connectedClients->row(list[0]));

    ui->logField->setPlainText(ui->logField->toPlainText() + "Client " + client + " disconnected from server.\n");
}

void MainWindow::addServer(QString server, int port){

    int rc = ui->connectedServers->rowCount();
    ui->connectedServers->insertRow(rc);

    QTableWidgetItem* newItemServer = new QTableWidgetItem(server);
    ui->connectedServers->setItem(rc, 0, newItemServer);
    ui->connectedServers->item(rc, 0)->setTextAlignment(Qt::AlignCenter);

    QTableWidgetItem* newItemPort = new QTableWidgetItem(QString("%1").arg(port));
    ui->connectedServers->setItem(rc, 1, newItemPort);
    ui->connectedServers->item(rc, 1)->setTextAlignment(Qt::AlignCenter);

    ui->logField->setPlainText(ui->logField->toPlainText() + "Local client connected to server " + server + " on port " + QString("%1").arg(port) + ".\n");
}

void MainWindow::removeServer(QString server){

    QList<QTableWidgetItem*> list = ui->connectedServers->findItems(server, Qt::MatchContains);

    ui->connectedServers->removeRow(ui->connectedServers->row(list[0]));

    ui->logField->setPlainText(ui->logField->toPlainText() + "Local client lost connection connected to server " + server + ".\n");

}

void MainWindow::newFileCliked(){

    NewFileDialog dialog;
    QString fileName;
    if(dialog.exec() == QDialog::Accepted){
        fileName = dialog.getFileName();
    }else
        return;

    if(fileName != ""){
        broadcastMessage(QString("%1").arg(ApplicationConfiguration::myHost.getId())+ ";" + "ZEGAR" + ";CreateFile;" + fileName);
    }
}

void MainWindow::logMessage(QString msg){
    ui->logField->setPlainText(ui->logField->toPlainText() + msg);
}
